import React, { useState, useEffect } from 'react';
import { Button, Divider } from 'antd';
import { useHistory } from 'react-router-dom';
import { LogoutOutlined, HomeOutlined, LoadingOutlined, RollbackOutlined } from '@ant-design/icons';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import logo from '../../../img/shipSRM/chlogo.png'
import { use_olseq_initformdata } from './use_sys_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';

const Olseq_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    kfkhdaOptions: [],
    wlda_cp: [], wlda_mj: [], gd_mjmx: []
  })

  //主表数据
  const [formdata, setformdata] = useState(use_olseq_initformdata)
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();

  //加载主表数据
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/sys/query_olseq_byid", 'POST', { id: id }, "json")
    console.log(rtdata.resultdata.formdata)
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
  }

  
  const loadformdata_copy = async (id) => {
    let rtdata = await fetchsync_util("/admin/sys/query_olseq_byid", 'POST', { id: id }, "json")
    console.log(rtdata.resultdata.formdata)
    var newformdata={ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) }
    newformdata.zt.value='未同步'
    setformdata(newformdata);
  }


  // 页面进入加载数据
  useEffect(() => {
    JSON.parse(storage.pre_olseq_item).type == "edit"||JSON.parse(storage.pre_olseq_item).type == "copy" ? loadformdata_copy(JSON.parse(storage.pre_olseq_item).data.id) : ""
    queryCdList()
}, [])
/**
 * 
 * 获取一级菜单列表
 * @returns 
 */
  const queryCdList = async () => {
    let rtdata = await fetchsync_util("/admin/sys/select_olseq", 'POST', {}, "json")
    var newformdata=formdata
     newformdata.parent_mc.selectdata=rtdata.resultdata
     setformdata({...newformdata})
  }

  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }


  const handleupload = async () => {


    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。
    
    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage);return; }
    else;
    //设置submit url
    var uploadurl = "";


      if (JSON.parse(storage.pre_olseq_item).type == "add"||
      JSON.parse(storage.pre_olseq_item).type == "copy") {
        uploadurl = "/admin/sys/add_olseq"
      }
      else if (JSON.parse(storage.pre_olseq_item).type == "edit") {
        uploadurl = "/admin/sys/update_olseq"
  
      }
      else;



    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
    dropByCacheKey("olseq_form")
    dropByCacheKey("olseq_list")
    setnowroute({route:"/shipSRM/sys/olseq_list",title:"在线序列",closeroute:"/shipSRM/sys/olseq_form"})

  }



  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}>



      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
        <br />


        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <Button type="primary" onClick={handleupload}
          style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem" }}>
          <SaveOutlined />{JSON.parse(storage.pre_olseq_item).type == "add" ? "保存" : "修改"}</Button>
        {/* 主表区域结束 */}
        <Divider></Divider>

      </div>
    </div>
  )
}


export default Olseq_form

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
    topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1vw",paddingRight:"1vw",height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: {paddingLeft:"1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%",fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw"},
  kshcontainer: {
    width: "98%", height: "95%", position: "absolute", top: "3%", left: "1%", backgroundColor: "white", color: "black",
    borderRadius: "10px",
  },
}
